package com.xjtu.mybatisplus.web.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjtu.mybatisplus.common.JsonResponse;
//import com.xjtu.mybatisplus.common.Result.PageResult;
import com.xjtu.mybatisplus.common.result.PageResult;
import com.xjtu.mybatisplus.common.result.Result;
import com.xjtu.mybatisplus.mapper.RoleMapper;
import com.xjtu.mybatisplus.model.dto.adminDto.PageInfoDto;
import com.xjtu.mybatisplus.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
//import com.xjtu.mybatisplus.common.Result;
import com.xjtu.mybatisplus.model.domain.User;



/**
 *
 *  前端控制器
 *
 *
 * @author lsong
 * @since 2023-12-27
 * @version v1.0
 */
@RestController
@RequestMapping("/api/admin")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger( UserController.class );

    @Autowired
    private UserService userService;

    @Autowired(required = false)
    private RoleMapper roleMapper;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        User  user =  userService.getById(id);
        return JsonResponse.success(user);
    }

    @GetMapping("/users")
    public JsonResponse<PageResult> getUsers(@RequestParam("page") Integer page, @RequestParam("size") Integer size,
                                       @RequestParam("content") String content) {
        // 将 JSON 字符串转换为 PageInfoDto 对象
        PageInfoDto pageInfoDto = new PageInfoDto();
        pageInfoDto.setPage(page);
        pageInfoDto.setSize(size);
        pageInfoDto.setContent(content);
        PageResult list = userService.getUsers(pageInfoDto);
        return JsonResponse.success(list);
    }
    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        userService.removeById(id);
        roleMapper.deleteUserRoleById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateUser(User  user) throws Exception {
        userService.updateById(user);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建User
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(User  user) throws Exception {
        userService.save(user);
        return JsonResponse.success(null);
    }
}

